package v1

import (
	"fmt"
	"gin_vue_blog/middleware"
	"gin_vue_blog/model"
	"gin_vue_blog/utils/errmsg"
	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v4"
	"time"
)

// 后台登录
func Login(c *gin.Context) {
	var formdata model.User
	_ = c.ShouldBindJSON(&formdata)
	fmt.Println("formdata:", formdata)
	var code int
	var token string
	formdata, code = model.Login(formdata.Username, formdata.Password)
	if code == errmsg.SUCCESS {
		setToken(c, formdata)
	} else {
		c.JSON(200, gin.H{
			"status":  code,
			"data":    formdata.Username,
			"id":      formdata.ID,
			"message": errmsg.GetErrMsg(code),
			"token":   token,
		})
	}
}

func LoginFront(c *gin.Context) {
	var formdata model.User
	_ = c.ShouldBindJSON(&formdata)
	user, code := model.LoginFront(formdata.Username, formdata.Password)
	c.JSON(200, gin.H{
		"status":  code,
		"data":    user.Username,
		"id":      user.ID,
		"message": errmsg.GetErrMsg(code),
	})
}

func setToken(c *gin.Context, user model.User) {
	j := middleware.NewJWT()
	claims := middleware.MyClaims{
		Username: user.Username,
		RegisteredClaims: jwt.RegisteredClaims{
			NotBefore: jwt.NewNumericDate(time.Now()),
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Minute * 10)), //10分钟过期
			Issuer:    "gin_vue_blog",
		},
	}
	token, err := j.CreateToken(claims)
	if err != nil {
		c.JSON(200, gin.H{
			"status":  errmsg.ERROR,
			"message": errmsg.GetErrMsg(errmsg.ERROR),
			"token":   token,
		})
		return
	}
	c.JSON(200, gin.H{
		"status":  errmsg.SUCCESS,
		"data":    user.Username,
		"id":      user.ID,
		"message": errmsg.GetErrMsg(errmsg.SUCCESS),
		"token":   token,
	})
}
